'use strict';

const dayjs = require("dayjs");

module.exports = app => {
  const { STRING, INTEGER, TINYINT, DATE } = app.Sequelize;

  const Student = app.model.define('Student', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    student_no: { type: STRING(20), allowNull: false, unique: true, comment: '学号' },
    name: { type: STRING(30), allowNull: false, comment: '学生姓名' },
    gender: { type: STRING(30), allowNull: false, defaultValue: '-', comment: '性别：1-男，2-女' },
    grade: { type: TINYINT(1), allowNull: false, comment: '年级' },
    class_name: { type: STRING(20), allowNull: false, comment: '班级' },
    parent_id: { type: INTEGER, comment: '关联家长ID' },
    status: { type: INTEGER, defaultValue: 1, comment: '状态：1-正常，0-禁用' },
    create_time: {
      type: DATE,
      get() {
        return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    updated_time: {
      type: DATE,
      get() {
        return dayjs(this.getDataValue('updated_time')).format('YYYY-MM-DD HH:mm:ss');
      }
    }
  }, {
    tableName: 'student',
    timestamps: true,
    updatedAt: 'updated_time',
    createdAt: 'create_time',
  });

  Student.associate = function() {
    // 关联家长信息
    app.model.Student.belongsTo(app.model.Parent, {
      foreignKey: 'parent_id',
      as: 'parent'
    });

    // 关联课程记录
    app.model.Student.hasMany(app.model.CourseRecord, {
      foreignKey: 'student_id',
      as: 'courseRecordList'
    });
  };

  return Student;
};
